import WPT from 'wpt';
import { exitFullScreen } from './util';

const { location } = window;
const CDNURL = 'https://media.weipaitang.com/';

// 全屏播放
function requestFullscreen(video) {
    if (video.requestFullscreen) {
        video.requestFullscreen();
    } else if (video.webkitRequestFullscreen) {
        video.webkitRequestFullscreen();
    }
}

/**
 * [playVideo 播放视频]
 * @method playVideo
 * @param  {DOM}  $dom     [description]
 * @param  {String|object}  src [视频路径]
 * @param  {Boolean}  playsinline [行内播放]
 * @param  {Boolean}  loop [循环播放]
 * @returns {HTMLVideoElement}
 */
export default function playVideo(
    $dom,
    src = '',
    playsinline = false,
    loop = false,
    needHide = false,
    isPreload = false
) {
    let option = {};
    let cover = '';

    if (typeof src === 'object') {
        option = src;
        src = option.src;
        playsinline = option.playsinline;
        loop = option.loop;
        needHide = option.needHide;
        cover = option.cover;
        isPreload = option.isPreload || false;
    }

    // 播放前
    option.onBeforePlay && option.onBeforePlay();

    $dom = $($dom);

    // 如果在wpt app内，使用系统播放器
    if ($.os.android && WPT.os.device == 'native') {
        option.onPlay && option.onPlay();
        // 不使用file转url，因为app暂时无法获取到资源地址，拼接使用
        if (/^blob/.test(src)) {
            // 使用资源线上原始地址
            src = location.protocol + CDNURL + $dom.parent().data('key');
        }
        // 使用本地播放器，播放视频
        window.wxx.playVideo(src);
        return;
    }

    if (!src) {
        console.error('视频地址不能为空');
        return;
    }

    // 关闭之前创建的video
    if ($.os.android) {
        // 安卓不使用行内播放
        $('.video-preview').remove();
    }

    // 对于行内播放，暂停不移除
    // 如果已有video 就播放video
    if ($dom.find('video').length) {
        option.onPlay && option.onPlay();
        $dom.find('video')[0].play();
        !playsinline
            && !navigator.userAgent.toLowerCase().match(/android|phone|ios/)
            && requestFullscreen($dom.find('video')[0]);
        return;
    }

    // 行内播放不显示loading
    // 版本大于等于363而且预加载了，则不显示loading
    !playsinline && !(WPT.os.wpt && WPT.os.wptAppVerison >= 365 && isPreload) && WPT.Modal.loading('视频加载中...');

    const $video = $(`<video class="video-preview"
            src="${src}"
            style="
                display: block;
                position: ${playsinline || !$.os.android ? 'absolute' : 'fixed'};
                top: 0;
                left: 0;
                z-index: 1000;
                width: ${$.os.ios || ($.os.android && playsinline) ? '0' : '100%'};
                height: auto;
                background-color: #000;
            "
            ${loop ? 'loop="true"' : ''}
            ${playsinline ? 'webkit-playsinline playsinline controls' : ''}
            x5-video-player-type=${playsinline ? 'h5-page' : 'h5'}
            x5-video-orientation="landscape|portrait"
            x5-video-player-fullscreen="true" >
        </video>`);

    if ($.os.android && playsinline === false) {
        $('body').append($video);
    } else {
        $dom.css({ postion: 'relative' }).append($video);
    }

    const video = $video[0];
    video.volume = 1;

    if (needHide) {
        video.style.objectFit = 'cover';
    }

    const STYLE_PLAY = {
        width: '100%',
        height: '100%',
        opacity: 1,
    };

    $.os.android && $video.css(STYLE_PLAY);

    let isVideoPlay = false;

    video._play = video.play;
    video.play = function p() {
        if (!WPT.wptBridge.playVideo({ cover, src })) {
            this._play();
        }
        WPT.Modal.loading.close();
    };

    $video
        .on('pause', function handlePause() {
            needHide && $.os.ios && $(this).remove();
            !playsinline && !WPT.os.pc && $(this).remove();
            option.onPause && option.onPause();
        })
        .on('ended', function handleEnd() {
            $(this).hide();
            exitFullScreen();
            $(this).remove();
            option.onEnd && option.onEnd();
        })
        .on('canplaythrough', function handleCanPlay() {
            if (!isVideoPlay) {
                isVideoPlay = true;
                WPT.Modal.loading.close();
                $(this).css(STYLE_PLAY);
                this.play();
                option.onPlay && option.onPlay();
            }
        })
        .on('click', e => {
            e.stopPropagation();
            e.preventDefault();
            if (video.paused) {
                video.play();
            } else {
                video.pause();
            }
        })
        .on('fullscreenchange', function () {
            if (!document.webkitIsFullScreen) {
                $(this).remove();
            }
        });

    // pc端请求全屏
    !playsinline && !navigator.userAgent.toLowerCase().match(/android|phone|ios/) && requestFullscreen(video);
    video.playPromise = video.play();
    // eslint-disable-next-line consistent-return
    return video;
}
